﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrnMall.Core;
using PetaPoco;

namespace BrnMall.Manager.Manager.Product
{
    /// <summary>
    /// 酒店预约商品库存检查
    /// </summary>
    public static class ProductBookStockManager
    {
        /// <summary>
        /// 库存检查
        /// </summary>
        /// <param name="pid">房型ID</param>
        /// <param name="bookTime">预定开始时间</param>
        /// <returns>当前日期已经预定了多少库存</returns>
        public static int GetBookStock(int pid, DateTime bookTime)
        {
            try
            {
                using (var db = new QDMallDatabase())
                {
                    var sql = new Sql();
                    sql.Select("count(a.book_number)");
                    sql.From("bma_orderproducts a");
                    sql.LeftJoin("bma_orders b on a.oid=b.oid ");
                    sql.Where(" a.pid=@1 and a.oid!=0 and b.orderstate!=160 and DATEDIFF(day,book_starttime, @0)>=0 and DATEDIFF(day,book_endtime, @0)<0  ",
                        bookTime,pid);
                    return db.ExecuteScalar<int>(sql);
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }
        /// <summary>
        /// 同步循环库存
        /// </summary>
        /// <param name="date"></param>
        public static void RecycleStock(DateTime date)
        {
            try
            {
                List<ProductStockInfo> list;
                using (var db = new QDMallDatabase())
                {
                    //取出需要循环库存的商品
                    list = db.Fetch<ProductStockInfo>("select * from bma_productstocks where isrecycle=1");
                }
                var sql = new StringBuilder();
                if (list == null) return;
                foreach (var stockInfo in list)
                {
                    var historyStock = GetBookStock(stockInfo.Pid, date);
                    var newStock = stockInfo.Number - historyStock;
                    if (newStock < 0) newStock = 0;
                    sql.AppendFormat(" update bma_productstocks set number={0} where pid={1}", newStock, stockInfo.Pid);
                }
                if (sql.Length <= 0) return;

                using (var db = new QDMallDatabase())
                {
                    db.Execute(sql.ToString());
                }

            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }
    }
}
